<template>
  <div class="abnormal-details">
    <div class="page-header">
      <h1>电梯异常详情</h1>
      <div class="header-actions">
        <t-date-range-picker
          v-model="dateRange"
          style="width: 300px; margin-right: 16px"
          :placeholder="['开始日期', '结束日期']"
          @change="handleDateRangeChange"
        />
        <t-select
          v-model="buildingFilter"
          style="width: 150px; margin-right: 16px"
          placeholder="选择楼栋"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部楼栋" />
          <t-option value="1号楼" label="1号楼" />
          <t-option value="2号楼" label="2号楼" />
          <t-option value="3号楼" label="3号楼" />
        </t-select>
        <t-select
          v-model="typeFilter"
          style="width: 150px; margin-right: 16px"
          placeholder="异常类型"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部类型" />
          <t-option value="振动异常" label="振动异常" />
          <t-option value="噪音异常" label="噪音异常" />
          <t-option value="温度异常" label="温度异常" />
          <t-option value="速度异常" label="速度异常" />
          <t-option value="电流异常" label="电流异常" />
          <t-option value="使用异常" label="使用异常" />
        </t-select>
        <t-input
          v-model="searchText"
          placeholder="搜索异常"
          style="width: 200px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="onSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <t-row :gutter="16">
      <t-col :span="16">
        <t-card title="异常事件列表" :bordered="true">
          <template #actions>
            <t-radio-group v-model="viewType">
              <t-radio-button value="all">全部</t-radio-button>
              <t-radio-button value="today">今日</t-radio-button>
              <t-radio-button value="week">本周</t-radio-button>
              <t-radio-button value="month">本月</t-radio-button>
            </t-radio-group>
          </template>
          
          <t-table
            :columns="columns"
            :data="filteredAbnormals"
            :loading="loading"
            :pagination="{ pageSize: 10 }"
            bordered
            row-key="id"
            hover
            @row-click="handleRowClick"
          >
            <template #type="{ row }">
              <t-tag :theme="getTypeTheme(row.type)" variant="light">
                {{ row.type }}
              </t-tag>
            </template>
            <template #level="{ row }">
              <t-tag :theme="getLevelTheme(row.level)" variant="light">
                {{ row.level }}
              </t-tag>
            </template>
            <template #status="{ row }">
              <t-tag :theme="getStatusTheme(row.status)" variant="light">
                {{ row.status }}
              </t-tag>
            </template>
            <template #op="{ row }">
              <t-space>
                <t-link theme="primary" hover="color" @click="handleView(row)">查看详情</t-link>
                <t-link theme="primary" hover="color" @click="handleMarkAsRead(row)" v-if="row.status === '未处理'">标记已读</t-link>
              </t-space>
            </template>
          </t-table>
        </t-card>
      </t-col>
      <t-col :span="8">
        <t-card :title="currentAbnormal ? '异常详情' : '请选择异常事件'" :bordered="true">
          <template v-if="!currentAbnormal">
            <t-empty description="请从左侧列表选择异常事件查看详情" />
          </template>
          <template v-else>
            <t-descriptions bordered>
              <t-descriptions-item label="异常ID">{{ currentAbnormal.id }}</t-descriptions-item>
              <t-descriptions-item label="发生时间">{{ currentAbnormal.time }}</t-descriptions-item>
              <t-descriptions-item label="电梯名称">{{ currentAbnormal.liftName }}</t-descriptions-item>
              <t-descriptions-item label="所在楼栋">{{ currentAbnormal.building }}</t-descriptions-item>
              <t-descriptions-item label="异常类型">
                <t-tag :theme="getTypeTheme(currentAbnormal.type)" variant="light">
                  {{ currentAbnormal.type }}
                </t-tag>
              </t-descriptions-item>
              <t-descriptions-item label="异常级别">
                <t-tag :theme="getLevelTheme(currentAbnormal.level)" variant="light">
                  {{ currentAbnormal.level }}
                </t-tag>
              </t-descriptions-item>
              <t-descriptions-item label="处理状态">
                <t-tag :theme="getStatusTheme(currentAbnormal.status)" variant="light">
                  {{ currentAbnormal.status }}
                </t-tag>
              </t-descriptions-item>
              <t-descriptions-item label="异常描述" :span="2">{{ currentAbnormal.description }}</t-descriptions-item>
            </t-descriptions>

            <div class="data-charts" v-if="currentAbnormal">
              <h3>异常数据分析</h3>
              <t-tabs default-value="trend">
                <t-tab-panel value="trend" label="数据趋势">
                  <div class="chart-placeholder">
                    <p>此处可集成图表组件展示异常数据趋势</p>
                  </div>
                </t-tab-panel>
                <t-tab-panel value="compare" label="对比分析">
                  <div class="chart-placeholder">
                    <p>此处可集成图表组件展示异常数据对比分析</p>
                  </div>
                </t-tab-panel>
              </t-tabs>
            </div>

            <div class="action-buttons">
              <t-space>
                <t-button theme="primary" @click="handleMarkAsRead(currentAbnormal)" v-if="currentAbnormal.status === '未处理'">标记已读</t-button>
                <t-button theme="default" @click="handleExportReport(currentAbnormal)">导出报告</t-button>
              </t-space>
            </div>
          </template>
        </t-card>
      </t-col>
    </t-row>

    <!-- 异常详情对话框 -->
    <t-dialog
      v-model:visible="detailsVisible"
      header="异常详情"
      :footer="false"
      width="800px"
    >
      <div v-if="currentAbnormal" class="abnormal-details-dialog">
        <t-descriptions bordered :column="2">
          <t-descriptions-item label="异常ID" :span="1">{{ currentAbnormal.id }}</t-descriptions-item>
          <t-descriptions-item label="发生时间" :span="1">{{ currentAbnormal.time }}</t-descriptions-item>
          <t-descriptions-item label="电梯名称" :span="1">{{ currentAbnormal.liftName }}</t-descriptions-item>
          <t-descriptions-item label="所在楼栋" :span="1">{{ currentAbnormal.building }}</t-descriptions-item>
          <t-descriptions-item label="异常类型" :span="1">
            <t-tag :theme="getTypeTheme(currentAbnormal.type)" variant="light">
              {{ currentAbnormal.type }}
            </t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="异常级别" :span="1">
            <t-tag :theme="getLevelTheme(currentAbnormal.level)" variant="light">
              {{ currentAbnormal.level }}
            </t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="处理状态" :span="1">
            <t-tag :theme="getStatusTheme(currentAbnormal.status)" variant="light">
              {{ currentAbnormal.status }}
            </t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="处理时间" :span="1">{{ currentAbnormal.processTime || '-' }}</t-descriptions-item>
          <t-descriptions-item label="异常描述" :span="2">{{ currentAbnormal.description }}</t-descriptions-item>
        </t-descriptions>

        <div class="abnormal-data">
          <h3>异常数据</h3>
          <t-row :gutter="16">
            <t-col :span="12">
              <div class="data-item">
                <div class="data-label">实际值</div>
                <div class="data-value">{{ currentAbnormal.actualValue }} {{ currentAbnormal.unit }}</div>
              </div>
            </t-col>
            <t-col :span="12">
              <div class="data-item">
                <div class="data-label">正常范围</div>
                <div class="data-value">{{ currentAbnormal.normalRange }} {{ currentAbnormal.unit }}</div>
              </div>
            </t-col>
          </t-row>
        </div>

        <div class="abnormal-charts">
          <h3>异常数据趋势</h3>
          <div class="chart-placeholder">
            <p>此处可集成图表组件展示异常数据趋势</p>
          </div>
        </div>

        <div class="abnormal-actions">
          <t-space>
            <t-button theme="primary" @click="handleMarkAsReadInDialog" v-if="currentAbnormal.status === '未处理'">标记已读</t-button>
            <t-button theme="default" @click="handleExportReport(currentAbnormal)">导出报告</t-button>
          </t-space>
        </div>
      </div>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    colKey: 'id',
    title: '异常ID',
    width: '80',
  },
  {
    colKey: 'time',
    title: '发生时间',
    width: '150',
    sorter: true,
  },
  {
    colKey: 'liftName',
    title: '电梯名称',
    width: '150',
  },
  {
    colKey: 'building',
    title: '所在楼栋',
    width: '100',
  },
  {
    colKey: 'type',
    title: '异常类型',
    width: '120',
    cell: 'type',
  },
  {
    colKey: 'level',
    title: '异常级别',
    width: '100',
    cell: 'level',
  },
  {
    colKey: 'status',
    title: '处理状态',
    width: '100',
    cell: 'status',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '160',
    cell: 'op',
  },
];

// 模拟异常数据
const abnormals = ref([
  {
    id: 'A001',
    time: '2023-09-18 08:15:32',
    liftName: '1号楼A电梯',
    building: '1号楼',
    type: '振动异常',
    level: '警告',
    status: '已处理',
    description: '电梯运行时振动值超出正常范围，可能存在机械故障',
    processTime: '2023-09-18 09:30:45',
    actualValue: '15.8',
    normalRange: '0-10',
    unit: 'mm/s²',
  },
  {
    id: 'A002',
    time: '2023-09-18 10:22:15',
    liftName: '2号楼B电梯',
    building: '2号楼',
    type: '噪音异常',
    level: '一般',
    status: '未处理',
    description: '电梯运行时噪音超出正常范围，可能存在机械摩擦',
    processTime: '',
    actualValue: '75',
    normalRange: '0-65',
    unit: 'dB',
  },
  {
    id: 'A003',
    time: '2023-09-18 11:05:48',
    liftName: '3号楼电梯',
    building: '3号楼',
    type: '温度异常',
    level: '严重',
    status: '未处理',
    description: '电梯电机温度过高，可能存在过载或散热不良',
    processTime: '',
    actualValue: '85',
    normalRange: '0-70',
    unit: '°C',
  },
  {
    id: 'A004',
    time: '2023-09-17 14:30:22',
    liftName: '1号楼B电梯',
    building: '1号楼',
    type: '速度异常',
    level: '警告',
    status: '已处理',
    description: '电梯运行速度波动较大，可能存在控制系统故障',
    processTime: '2023-09-17 16:15:30',
    actualValue: '1.8',
    normalRange: '1.5±0.1',
    unit: 'm/s',
  },
  {
    id: 'A005',
    time: '2023-09-17 09:12:38',
    liftName: '2号楼A电梯',
    building: '2号楼',
    type: '电流异常',
    level: '一般',
    status: '已处理',
    description: '电梯电机电流波动，可能存在负载不均',
    processTime: '2023-09-17 10:45:22',
    actualValue: '25.5',
    normalRange: '15-22',
    unit: 'A',
  },
  {
    id: 'A006',
    time: '2023-09-16 16:45:10',
    liftName: '1号楼A电梯',
    building: '1号楼',
    type: '使用异常',
    level: '一般',
    status: '未处理',
    description: '电梯频繁启停，可能存在使用不当',
    processTime: '',
    actualValue: '45',
    normalRange: '0-30',
    unit: '次/小时',
  },
  {
    id: 'A007',
    time: '2023-09-16 11:20:45',
    liftName: '2号楼B电梯',
    building: '2号楼',
    type: '振动异常',
    level: '警告',
    status: '已处理',
    description: '电梯运行时振动值超出正常范围，可能存在机械故障',
    processTime: '2023-09-16 13:40:15',
    actualValue: '12.5',
    normalRange: '0-10',
    unit: 'mm/s²',
  },
  {
    id: 'A008',
    time: '2023-09-15 09:05:30',
    liftName: '3号楼电梯',
    building: '3号楼',
    type: '温度异常',
    level: '严重',
    status: '已处理',
    description: '电梯电机温度过高，可能存在过载或散热不良',
    processTime: '2023-09-15 10:30:45',
    actualValue: '90',
    normalRange: '0-70',
    unit: '°C',
  },
]);

const loading = ref(false);
const dateRange = ref([]);
const buildingFilter = ref('');
const typeFilter = ref('');
const searchText = ref('');
const viewType = ref('all');
const detailsVisible = ref(false);
const currentAbnormal = ref(null);

// 根据筛选条件过滤异常
const filteredAbnormals = computed(() => {
  let result = [...abnormals.value];
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2 && dateRange.value[0] && dateRange.value[1]) {
    const startDate = dayjs(dateRange.value[0]).startOf('day');
    const endDate = dayjs(dateRange.value[1]).endOf('day');
    result = result.filter(abnormal => {
      const abnormalDate = dayjs(abnormal.time);
      return abnormalDate.isAfter(startDate) && abnormalDate.isBefore(endDate);
    });
  }
  
  // 按视图类型筛选
  if (viewType.value !== 'all') {
    const today = dayjs().startOf('day');
    const weekStart = dayjs().startOf('week');
    const monthStart = dayjs().startOf('month');
    
    result = result.filter(abnormal => {
      const abnormalDate = dayjs(abnormal.time);
      if (viewType.value === 'today') {
        return abnormalDate.isAfter(today);
      } else if (viewType.value === 'week') {
        return abnormalDate.isAfter(weekStart);
      } else if (viewType.value === 'month') {
        return abnormalDate.isAfter(monthStart);
      }
      return true;
    });
  }
  
  // 按楼栋筛选
  if (buildingFilter.value) {
    result = result.filter(abnormal => abnormal.building === buildingFilter.value);
  }
  
  // 按异常类型筛选
  if (typeFilter.value) {
    result = result.filter(abnormal => abnormal.type === typeFilter.value);
  }
  
  // 按搜索文本筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(
      (abnormal) =>
        abnormal.liftName.toLowerCase().includes(keyword) ||
        abnormal.type.toLowerCase().includes(keyword) ||
        abnormal.description.toLowerCase().includes(keyword) ||
        abnormal.id.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

// 获取异常类型对应的主题色
const getTypeTheme = (type) => {
  switch (type) {
    case '振动异常': return 'warning';
    case '噪音异常': return 'warning';
    case '温度异常': return 'danger';
    case '速度异常': return 'warning';
    case '电流异常': return 'warning';
    case '使用异常': return 'default';
    default: return 'default';
  }
};

// 获取异常级别对应的主题色
const getLevelTheme = (level) => {
  switch (level) {
    case '严重': return 'danger';
    case '警告': return 'warning';
    case '一般': return 'default';
    default: return 'default';
  }
};

// 获取处理状态对应的主题色
const getStatusTheme = (status) => {
  switch (status) {
    case '未处理': return 'danger';
    case '已处理': return 'success';
    default: return 'default';
  }
};

// 日期范围变化处理
const handleDateRangeChange = (value) => {
  dateRange.value = value;
};

// 筛选条件变化处理
const handleFilterChange = () => {
  // 筛选逻辑已通过计算属性实现
};

// 搜索处理
const onSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 行点击处理
const handleRowClick = (row) => {
  currentAbnormal.value = { ...row };
};

// 查看异常详情
const handleView = (row) => {
  currentAbnormal.value = { ...row };
  detailsVisible.value = true;
};

// 标记为已读
const handleMarkAsRead = (row) => {
  const index = abnormals.value.findIndex(item => item.id === row.id);
  if (index !== -1) {
    abnormals.value[index].status = '已处理';
    abnormals.value[index].processTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    
    // 如果当前选中的是这个异常，也更新当前异常的状态
    if (currentAbnormal.value && currentAbnormal.value.id === row.id) {
      currentAbnormal.value.status = '已处理';
      currentAbnormal.value.processTime = abnormals.value[index].processTime;
    }
    
    MessagePlugin.success('异常已标记为已读');
  }
};

// 在对话框中标记为已读
const handleMarkAsReadInDialog = () => {
  handleMarkAsRead(currentAbnormal.value);
  detailsVisible.value = false;
};

// 导出报告
const handleExportReport = (row) => {
  MessagePlugin.info('正在导出异常报告...');
  setTimeout(() => {
    MessagePlugin.success('异常报告导出成功');
  }, 1000);
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取异常列表的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.abnormal-details {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.header-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.data-charts {
  margin-top: 24px;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  margin-top: 16px;
}

.action-buttons {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.abnormal-details-dialog {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.abnormal-data {
  margin-top: 16px;
}

.data-item {
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 4px;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.data-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.data-value {
  font-size: 24px;
  font-weight: 500;
}

.abnormal-charts {
  margin-top: 16px;
}

.abnormal-actions {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
</style> 